package es.truscoandrisco.discotecasmadrid;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.curso.android.SocialConnector.Facebook.BaseRequestListener;
import com.curso.android.SocialConnector.Facebook.SessionEvents;
import com.curso.android.Utils.SDKFacebook.AsyncFacebookRunner;
import com.curso.android.Utils.SDKFacebook.DialogError;
import com.curso.android.Utils.SDKFacebook.Facebook;
import com.curso.android.Utils.SDKFacebook.FacebookError;
import com.curso.android.Utils.SDKFacebook.Facebook.DialogListener;


public class Cercanas extends ListActivity{
	
	private static ArrayList<Discoteca> arrayDisco = new ArrayList<Discoteca>();   
	private static MyAdapter mAdapter = null;
	static Drawable[] arrayLogos = new Drawable[20];
	static boolean visitedLogos[] = new boolean[20];
	private static String URL_MY_STATUS = "me/feed/";
	final Facebook mFacebook = new Facebook("17...");
	private Activity mActivity;
	private LocationManager lm;
	private LocationListener ll;
	private ProgressDialog pd;
	private Location location;
	private Context mContext;
	   
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		mActivity = this;
		mContext = getApplicationContext();
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		mAdapter = new MyAdapter(this);

		refreshList();
		
		registerForContextMenu(getListView());
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
    private class MyLocationListener implements LocationListener{

		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub

			if (loc != null) {
				pd.dismiss();	
				location = loc;
				new getListElements().execute();
			}
			lm.removeUpdates(ll);
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub		
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}	
    }
	
///////////////////////////////////////////////////////////////////////////////////////////////////////	


	public void refreshList(){
        
		for (int i = 0; i < 20; i++){
        	visitedLogos[i] = false;
        }
		
		if (! lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Necesita activar el GPS")
			       .setCancelable(false)
			       .setPositiveButton("Activar", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   Intent settingsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);        	   
			        	   startActivity(settingsIntent);
			        	   setListAdapter(mAdapter);
			           }
			       })
			       .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			                setListAdapter(mAdapter);
			           }
			       }).show();
		}else{
		    pd = new ProgressDialog(this);
		    pd.setTitle("Por favor espere...");
		    pd.setMessage("Buscando ubicación...");
		    pd.setButton("Cancelar", new DialogInterface.OnClickListener(){
		        public void onClick(DialogInterface dialog, int which){
		        	location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		        	if (location != null){
		        		lm.removeUpdates(ll);
					Toast.makeText(getBaseContext(),
						    "Usando última posición conocida",
							Toast.LENGTH_SHORT).show();
		        	}else{
						Toast.makeText(getBaseContext(), "No ubicado", Toast.LENGTH_SHORT).show();
		        		lm.removeUpdates(ll);
		        	}
		        	lm.removeUpdates(ll);
		        	new getListElements().execute();
		        }
		    });
		    
		    pd.show();

			lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);		 
			ll = new MyLocationListener();	 
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
		}
		
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////

	public String getPosActual(Location location){
		String longitud, latitud, posactual;
		
		posactual = "";
		
		if (location != null){
			int dLatitud = (int) (location.getLatitude() * 1000000);
			int dLongitud = (int) (location.getLongitude() * 1000000);
			
			if (dLatitud > 0) 
				latitud  = "+".concat(String.valueOf(dLatitud));
			else 
				latitud =  String.valueOf(dLatitud);
				
			if (dLongitud > 0)
				longitud  = "+".concat(String.valueOf(dLongitud));
			else 
				longitud = String.valueOf(dLongitud);
			
			posactual =  latitud + "lon" + longitud;
			
		}
		
		return posactual;
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	   
		private class getListElements extends AsyncTask<Void, Void, Void>{
				
				ProgressDialog pd;
				
				protected void onPreExecute(){
					pd = ProgressDialog.show(Cercanas.this, "Por favor espere...",
												"Buscando discotecas cercanas...", true);
				}

				@Override
				protected Void doInBackground(Void... arg0) {
					// TODO Auto-generated method stub
					
					if (! getPosActual(location).equals("")) {
						MyJSONParser mjp = new MyJSONParser();
						String url = "http://..." + getPosActual(location);
						String str = mjp.doGet(url);
						arrayDisco = mjp.parse(str);
					}
					
					return null;
				}
				
				protected void onPostExecute(Void unused){
					if (!isFinishing()){
						pd.dismiss();
						setListAdapter(mAdapter);
						if (arrayDisco.size() == 0 && location != null){
							Toast.makeText(getApplicationContext(), "No hay discotecas cerca de aquí",
									Toast.LENGTH_LONG).show();
						}
						mAdapter.notifyDataSetChanged();
					}
				}
			
			}
		
//////////////////////////////////////////////////////////////////////////////////////////////////////

			private static class downloadIcon extends AsyncTask<Integer, Void, Void> {

				@Override
				protected Void doInBackground(Integer... params) {
					Integer position = params[0];
					
					if ((arrayDisco != null) && (arrayDisco.size() > position)){ 	

						String url = "http://..." + arrayDisco.get(position).getNombre() + "...jpg";
						
						try {
							arrayLogos[position] = arrayDisco.get(position).setImagenImg(url, "");
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					return null;
				}
				
				protected void onPostExecute(Void unused) {			
					mAdapter.notifyDataSetChanged();
				}    
			
			}

//////////////////////////////////////////////////////////////////////////////////////////////////////

		public class MyAdapter extends BaseAdapter {
	        //Creamos la clase adaptador
			private Context mContext;

			public MyAdapter(Context c) {
				mContext = c;
			}

			//@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return arrayDisco.size()+1;
			}

			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return null;
			}

			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return 0;
			}
			
			public View getView(int position, View convertView, ViewGroup parent){
				
				View view;
				LayoutInflater inflater;
				
				if (position == 0){
					inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.myfirstitem, null);
					Button act = (Button) view.findViewById(R.id.act);
					
					act.setText("Actualizar");
					
					act.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							refreshList();
						}
					});
					
				}else{
					inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.myitem, null);		
		
					
					ImageView imgv = (ImageView) view.findViewById(R.id.image);
					
					if (visitedLogos[position-1] == false){
						new downloadIcon().execute(position-1);
						visitedLogos[position-1] = true;
					}else{
						imgv.setImageDrawable(arrayLogos[position-1]);
					}
						
					TextView t = (TextView) view.findViewById(R.id.title);
					t.setText(arrayDisco.get(position-1).getNombre());
					
					ImageView premium = (ImageView) view.findViewById(R.id.premium);
					
					if (arrayDisco.get(position-1).getPremium().equals("si")){
						premium.setImageDrawable(mContext.getResources().getDrawable(R.drawable.premium));
					}else
						premium.setImageDrawable(null);
							
					t = (TextView) view.findViewById(R.id.evento);
					t.setText(arrayDisco.get(position-1).getDireccion());
					
					t = (TextView) view.findViewById(R.id.zona);
					t.setText(arrayDisco.get(position-1).getLogo());
					
					t = (TextView) view.findViewById(R.id.musica);
					t.setText(arrayDisco.get(position-1).getImagen());
				}
				
				return view;
		
			}
	}

		
//////////////////////////////////////////////////////////////////////////////////////////////////////
		
		 protected void onListItemClick(ListView l, View v, int position, long id){
			 	
			 	final int pos = position-1;
			 	
				if (arrayDisco.get(position-1).getPremium().equals("si")) {
				    Intent i = new Intent(this, DiscoActivity.class);
					
					i.putExtra("DESCRIPCION", arrayDisco.get(pos).getDescripcion());
					i.putExtra("EVENTO1", arrayDisco.get(pos).getEvento1());
					i.putExtra("EVENTO2", arrayDisco.get(pos).getEvento2());
					i.putExtra("NOMBRE", arrayDisco.get(pos).getNombre());
					i.putExtra("DIRECCION", arrayDisco.get(pos).getDireccion());
					i.putExtra("LATITUD", arrayDisco.get(pos).getLatitud());
					i.putExtra("LONGITUD", arrayDisco.get(pos).getLongitud());
		
					startActivity(i);
				} else {
					final CharSequence[] items = {"Ver mapa", "Publicar en Facebook"};

					AlertDialog.Builder builder = new AlertDialog.Builder(Cercanas.this);
					builder.setTitle("Selecciona la opción: ");
					builder.setItems(items, new DialogInterface.OnClickListener() {		
						public void onClick(DialogInterface dialog, int item) {
							if (item == 0){
							    Intent i = new Intent(mContext, mapas.class);
								i.putExtra("LATITUD", arrayDisco.get(pos).getLatitud());
								i.putExtra("LONGITUD", arrayDisco.get(pos).getLongitud());
							    i.putExtra("NOMBRE", arrayDisco.get(pos).getNombre());
								startActivity(i);

							}else{
								String [] permissions = new String[2];
						       	permissions[0] = "publish_stream";
						       	permissions[1] = "read_stream";	
						        String nombre = arrayDisco.get(pos).getNombre();
								final CharSequence item1 = "Estoy pensando en ir a " + nombre + " esta noche...";
								final CharSequence item2 = "Esta noche voy a ir a " + nombre;
								final CharSequence item3 = "Estoy yendo a " + nombre;
								final CharSequence item4 = "Estoy en " + nombre;
								
								final CharSequence[] items = {item1, item2, item3, item4};

								AlertDialog.Builder builder = new AlertDialog.Builder(Cercanas.this);
								builder.setTitle("Selecciona el mensaje: ");
								builder.setItems(items, new DialogInterface.OnClickListener() {
									
								public void onClick(DialogInterface dialog, int item) {

						        	String status = (String) items[item];
						        		
								    if (updateStatus(status))
								        Toast.makeText(getApplicationContext(), "Mensaje publicado correctamente",
								        		Toast.LENGTH_SHORT).show();
								    else
									    Toast.makeText(getApplicationContext(), "El mensaje no ha podido ser publicado",
									        	Toast.LENGTH_SHORT).show();
								    }
								});
								
								AlertDialog alert = builder.create();
								alert.show();
								
								if (!mFacebook.isSessionValid())
									mFacebook.authorize(mActivity, permissions, new LoginDialogListener());
							    }
							}
						});
					
					AlertDialog alert = builder.create();
					alert.show();
				}
		 }		
		
		 
//////////////////////////////////////////////////////////////////////////////////////////////////////
		 
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.menu, menu);
	        return true;
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle item selection
	        switch (item.getItemId()) {
	        case R.id.Actualizar:
	            refreshList();
	            return true;
	        case R.id.about:
	        	Intent i = new Intent(this, About.class);
	        	startActivity(i);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	        }
	    }
	    
	    
//////////////////////////////////////////////////////////////////////////////////////////////////////	    
		
		private final class LoginDialogListener implements DialogListener {
	        public void onComplete(Bundle values) {
	            SessionEvents.onLoginSuccess();
	            // 0 -> session doesn't expire.
	            mFacebook.setAccessExpires(0);
	        }

	        public void onFacebookError(FacebookError error) {
	            SessionEvents.onLoginError(error.getMessage());
	        }
	        
	        public void onError(DialogError error) {
	            SessionEvents.onLoginError(error.getMessage());
	        }

	        public void onCancel() {
	            SessionEvents.onLoginError("Action Canceled");
	        }
	    }
		
		private boolean updateStatus(String newStatus){
			if (!mFacebook.isSessionValid() || newStatus.trim().equals("")) {	
				return false;
			}else{			
				Bundle bundle = new Bundle();
				bundle.putString("message", newStatus.trim());
				try{
					AsyncFacebookRunner async = new AsyncFacebookRunner(mFacebook);
					async.request(URL_MY_STATUS, bundle, "POST", new UpdateMyStatusListener());
				}catch(Exception ex){
					return false;
				}
			}
			return true;
		}
		
		public class UpdateMyStatusListener extends BaseRequestListener {
	        public void onComplete(final String response) {
	        }
	    }
		 
}
